package com.android.gtdroid;

import java.util.ArrayList;
import java.util.HashMap;

import android.app.Activity;
import android.app.AlertDialog;
import android.app.AlertDialog.Builder;
import android.app.Dialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.database.Cursor;
import android.graphics.Color;
import android.os.Bundle;
import android.util.Log;
import android.view.ContextMenu;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.Window;
import android.view.WindowManager;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.AdapterView.OnItemLongClickListener;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ListView;
import android.widget.SimpleAdapter;
import android.widget.TextView;

public class ListAct extends Activity {

	final Window window = getWindow();
	private ArrayList<HashMap<String, Object>> items = new ArrayList<HashMap<String, Object>>();
	public SimpleAdapter sa;
	private ListItem selected;
	private long posInTable;
	public static Dialog dlg;
	private ListView list_view;
	private GTDApp ga;
	private TextView currentTV;
	private int bottomTag;

	public static final int MENU_COMPLETED = Menu.FIRST;
	public static final int MENU_TRASH = Menu.FIRST + 1;

	public static int FLAG = 0;
	public static final int MENU_ID_ADD = Menu.FIRST;
	public static final int MENU_ID_EDIT = Menu.FIRST + 1;
	public static final int MENU_ID_DELETE = Menu.FIRST + 2;
	public static final int DLG_ID_EDIT = 0;
	public static final int DLG_ID_ADD = 1;
	private final String[] fromCols = new String[] { "item_name", "item_note" };
	private final int[] toLayouts = new int[] { R.id.item_name, R.id.item_note };
	private final String tag = "ListAct";

	/* Called when the activity is first created. */
	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);

		Log.i(tag, "now create method is called!");

		// set window title
//		boolean useTitleFeature = false;
//		if (window.getContainer() == null) {
//			useTitleFeature = window.requestFeature(Window.FEATURE_CUSTOM_TITLE);
//		}
		
		setContentView(R.layout.main1);
		
//		if (useTitleFeature) {
//			window.setFeatureInt(Window.FEATURE_CUSTOM_TITLE, R.layout.tb_main);
//		}
//		
		/*requestWindowFeature(Window.FEATURE_CUSTOM_TITLE);
		getWindow()
				.setFeatureInt(Window.FEATURE_CUSTOM_TITLE, R.layout.tb_main);*/

		currentTV = (TextView) findViewById(R.id.lists);
		bottomTag = R.id.tv_tag_list;
		// setBottomBar();
		handleEvent();

		ga = (GTDApp) getApplication(); // open database
		if (ga == null)
			Log.i(tag, "ga is null!!");

		if (!ga.getDb().isOpen())
			Log.i(tag, "database is closed in onCreate!");
		else
			Log.i(tag, "database is opened in onCreate");
		// ga.getDbla().removeAllList(); // for test
		// items.clear();

		list_view = (ListView) findViewById(R.id.lists_view);
		sa = new SimpleAdapter(this, items, R.layout.list_item, fromCols,
				toLayouts);
		list_view.setAdapter(sa);
		updateAdapterData();

		processListView();

		// registerForContextMenu(list_view);
	}

	@Override
	protected void onStart() {
		// TODO Auto-generated method stub
		super.onStart();
		Log.i(tag, "now start method is called!");
	}

	@Override
	protected void onPause() {
		// TODO Auto-generated method stub
		super.onPause();
		Log.i(tag, "now pause method is called!");
	}

	@Override
	protected void onResume() {
		// TODO Auto-generated method stub
		super.onResume();
		Log.i(tag, "now resume method is called!");
	}

	@Override
	protected void onStop() {
		// TODO Auto-generated method stub
		super.onStop();
		Log.i(tag, "now stop method is called!");

		// savePreferences();
	}

	@Override
	protected void onRestart() {
		// TODO Auto-generated method stub
		super.onRestart();
		Log.i(tag, "now restart method is called!");
	}

	@Override
	protected void onDestroy() {
		// TODO Auto-generated method stub

		Log.i(tag, "now destroy method is called!");

		// if (ga.getListCursor() != null)
		// ga.getListCursor().close();
		// if (ga.getTaskCursor() != null)
		// ga.getTaskCursor().close();
		// if (ga.getDbHelper() != null)
		// ga.getDbHelper().close();
		// if (ga.getDb()!=null && ga.getDb().isOpen())
		// ga.getDb().close();

		super.onDestroy();

		// System.exit(0);
	}

	protected void dialog() {
		AlertDialog.Builder builder = new Builder(this);
		builder.setMessage("ȷ��Ҫ�˳���?");
		builder.setTitle("��ʾ");
		builder.setPositiveButton("ȷ��",
				new android.content.DialogInterface.OnClickListener() {
					@Override
					public void onClick(DialogInterface dialog, int which) {
						dialog.dismiss();
						finish();
					}
				});
		builder.setNegativeButton("ȡ��",
				new android.content.DialogInterface.OnClickListener() {
					@Override
					public void onClick(DialogInterface dialog, int which) {
						dialog.dismiss();
					}
				});
		builder.create().show();
	}

	private void handleEvent() {
		/*
		 Button btn_home = (Button) findViewById(R.id.btn_home);
		 btn_home.setOnClickListener(new Button.OnClickListener() { public
		 void onClick(View v) {
			 Intent itt = new Intent(); //
			 itt.setClass(ListAct.this, ViewTaskAct.class);
		
			 startActivity(itt);
			 }
		 });*/
		
		Button new_task = (Button) getParent().findViewById(R.id.new_task);
		new_task.setOnClickListener(new Button.OnClickListener() {
			public void onClick(View v) { // setTitle("intent");
				Intent itt = new Intent(ListAct.this, NewTaskAct.class);
				startActivityForResult(itt, 0);
			}
		});
		 
	}

	private void processListView() {
		// has been disabled
		OnItemLongClickListener oilsl = new OnItemLongClickListener() {
			public boolean onItemLongClick(AdapterView<?> parent, View v,
					int pos, long id) {
				// TODO Auto-generated method stub
				@SuppressWarnings("unchecked")
				HashMap<String, Object> hm = (HashMap<String, Object>) list_view
						.getItemAtPosition(pos);
				posInTable = ((Long) hm.get("item_index")).longValue();
				String list_name = (String) hm.get("item_name");
				String list_note = (String) hm.get("item_note");
				selected = new ListItem(list_name, list_note);
				// setTitle("long click"+current_str);

				return false;
			}
		};
		list_view.setOnItemLongClickListener(oilsl);

		// will show task list
		OnItemClickListener oicl = new OnItemClickListener() {
			public void onItemClick(AdapterView<?> parent, View v, int pos,
					long id) {
				// TODO Auto-generated method stub
				@SuppressWarnings("unchecked")
				HashMap<String, Object> hm = (HashMap<String, Object>) list_view
						.getItemAtPosition(pos);
				posInTable = ((Long) hm.get("item_index")).longValue();
				selected = ga.getDbla().getListItem(posInTable);
				// String listName = selected.getListName();

				Intent itt = new Intent(ListAct.this, ViewTaskAct.class);

				itt.putExtra("list_index", pos);
				itt.putExtra("list_status", C.TASK.UNCOMPLETED);

				// startActivityForResult(itt, 0);
				startActivity(itt);
			}
		};
		list_view.setOnItemClickListener(oicl);
	}

	public void setBottomBar() {
		final TextView lists = (TextView) findViewById(R.id.lists);
		/*
		 * lists.setOnClickListener(new View.OnClickListener() { public void
		 * onClick(View v) { // TODO Auto-generated method stub //
		 * setTitle("lists"); currentTV.setBackgroundColor(Color.TRANSPARENT);
		 * ((TextView)
		 * findViewById(bottomTag)).setBackgroundColor(Color.TRANSPARENT);
		 * 
		 * currentTV = (TextView) v; currentTV.setBackgroundColor(Color.DKGRAY);
		 * bottomTag = R.id.tv_tag_list; ((TextView)
		 * findViewById(bottomTag)).setBackgroundColor(Color.LTGRAY); } });
		 */

		/*
		 * final TextView agenda = (TextView) findViewById(R.id.agenda);
		 * agenda.setOnClickListener(new View.OnClickListener() { public void
		 * onClick(View v) { // TODO Auto-generated method stub //
		 * setTitle("agenda"); currentTV.setBackgroundColor(Color.TRANSPARENT);
		 * ((TextView)
		 * findViewById(bottomTag)).setBackgroundColor(Color.TRANSPARENT);
		 * 
		 * currentTV = (TextView) v; currentTV.setBackgroundColor(Color.DKGRAY);
		 * bottomTag = R.id.tv_tag_agenda; ((TextView)
		 * findViewById(bottomTag)).setBackgroundColor(Color.LTGRAY); } });
		 */

		final TextView contexts = (TextView) findViewById(R.id.contexts);
		contexts.setOnClickListener(new View.OnClickListener() {
			public void onClick(View v) {
				// TODO Auto-generated method stub
				// setTitle("contexts");
				currentTV.setBackgroundColor(Color.TRANSPARENT);
				((TextView) findViewById(bottomTag))
						.setBackgroundColor(Color.TRANSPARENT);

				currentTV = (TextView) v;
				currentTV.setBackgroundColor(Color.DKGRAY);
				bottomTag = R.id.tv_tag_context;
				((TextView) findViewById(bottomTag))
						.setBackgroundColor(Color.LTGRAY);

				Intent itt = new Intent(ListAct.this, ContextAct.class);
				startActivity(itt);
			}
		});
		final TextView search = (TextView) findViewById(R.id.search);
		search.setOnClickListener(new View.OnClickListener() {
			public void onClick(View v) {
				// TODO Auto-generated method stub
				// setTitle("search");
				currentTV.setBackgroundColor(Color.TRANSPARENT);
				((TextView) findViewById(bottomTag))
						.setBackgroundColor(Color.TRANSPARENT);

				currentTV = (TextView) v;
				currentTV.setBackgroundColor(Color.DKGRAY);
				bottomTag = R.id.tv_tag_search;
				((TextView) findViewById(bottomTag))
						.setBackgroundColor(Color.LTGRAY);
			}
		});
		final TextView more = (TextView) findViewById(R.id.more);
		more.setOnClickListener(new View.OnClickListener() {
			public void onClick(View v) {
				// TODO Auto-generated method stub
				// setTitle("more");
				currentTV.setBackgroundColor(Color.TRANSPARENT);
				((TextView) findViewById(bottomTag))
						.setBackgroundColor(Color.TRANSPARENT);

				currentTV = (TextView) v;
				currentTV.setBackgroundColor(Color.DKGRAY);
				bottomTag = R.id.tv_tag_more;
				((TextView) findViewById(bottomTag))
						.setBackgroundColor(Color.LTGRAY);
			}
		});
	}

	private void updateAdapterData() {
		HashMap<String, Object> hm;

		if (!ga.getDb().isOpen()) { // database is closed
			Log.i(tag, "database is closed!");
			ga.getDb().acquireReference();
		} else
			Log.i(tag, "database is opened!");
		Cursor csr = ga.getDbla().getAllListItems();
		// startManagingCursor(csr);
		if (csr.getCount() == 0) { // initialize lists only when (will cause
									// database close automatically
									// there is no list
			ga.initLists();
			csr = ga.getDbla().getAllListItems(); // requery cursor
		}

		items.clear();
		if (csr.moveToFirst()) {
			do {
				long rowId = csr.getLong(DBListAdapter.COL_ID);
				String list = csr.getString(DBListAdapter.COL_LIST_NAME);
				String note = csr.getString(DBListAdapter.COL_LIST_NOTE);
				hm = new HashMap<String, Object>();
				hm.put("item_index", rowId);
				hm.put("item_name", list);
				hm.put("item_note", note);
				items.add(hm);
			} while (csr.moveToNext());
		}
		sa.notifyDataSetChanged();
	}

	@Override
	public void onCreateContextMenu(ContextMenu menu, View v,
			ContextMenu.ContextMenuInfo menuInfo) {
		super.onCreateContextMenu(menu, v, menuInfo);
		menu.setHeaderTitle("�༭�б�");
		menu.add(0, MENU_ID_ADD, Menu.NONE, "���");
		menu.add(0, MENU_ID_EDIT, Menu.NONE, "������");
		menu.add(0, MENU_ID_DELETE, Menu.NONE, "ɾ��");
	}

	@Override
	public Dialog onCreateDialog(int id) {
		Window window;

		switch (id) {
		case (DLG_ID_EDIT):
			dlg = new Dialog(this);
			window = dlg.getWindow();
			window.setFlags(WindowManager.LayoutParams.FLAG_BLUR_BEHIND,
					WindowManager.LayoutParams.FLAG_BLUR_BEHIND);
			dlg.setTitle("������");
			dlg.setContentView(R.layout.dialog_view);

			return dlg;

		case (DLG_ID_ADD):
			dlg = new Dialog(this);
			window = dlg.getWindow();
			window.setFlags(WindowManager.LayoutParams.FLAG_BLUR_BEHIND,
					WindowManager.LayoutParams.FLAG_BLUR_BEHIND);
			dlg.setTitle("����б�");
			dlg.setContentView(R.layout.dialog_view);

			return dlg;
		}

		return null;
	}

	@Override
	public void onPrepareDialog(int id, Dialog dialog) {
		Button btn_ok = (Button) dlg.findViewById(R.id.btn_ok);
		Button btn_cal = (Button) dlg.findViewById(R.id.btn_cal);
		EditText text = (EditText) dlg.findViewById(R.id.dlg_edit_text);

		btn_cal.setOnClickListener(new Button.OnClickListener() {
			public void onClick(View v) {
				dlg.dismiss();
			}
		});

		switch (id) {
		case (DLG_ID_EDIT):
			text.setText(selected.getListName());
			text.selectAll();

			btn_ok.setOnClickListener(new Button.OnClickListener() {
				public void onClick(View v) {
					EditText et = (EditText) dlg
							.findViewById(R.id.dlg_edit_text);
					String str = et.getText().toString();
					// ga.listItems.set(posInTable, new
					// ListItem(str,selected.getListNote()));
					ga.getDbla().updateList(posInTable,
							new ListItem(str, selected.getListNote()));
					// listCursor = dbla.getAllListItems();
					// ga.updateLists();
					updateAdapterData();
					// setTitle("hello!!");
					dlg.dismiss();
				}
			});

			break;
		case (DLG_ID_ADD):
			text.setText("");
			text.setFocusable(true);

			btn_ok.setOnClickListener(new Button.OnClickListener() {
				public void onClick(View v) {
					EditText et = (EditText) dlg
							.findViewById(R.id.dlg_edit_text);
					String str = et.getText().toString();
					if (str.length() > 0) {
						// ga.listItems.add(new
						// ListItem(str,selected.getListNote()));
						ga.getDbla().insertList(new ListItem(str, ""));
						// ga.getListCursor() = ga.getDbla().getAllListItems();
						// ga.updateLists();
						updateAdapterData();
						// setTitle("add list:"+str);
					} else {

					}
					dlg.dismiss();
				}
			});

			break;
		}
	}

	// select one menu item
	public boolean onContextItemSelected(MenuItem item) {
		super.onContextItemSelected(item);

		switch (item.getItemId()) {
		case (MENU_ID_ADD): {
			showDialog(DLG_ID_ADD);
			return true;
		}
		case (MENU_ID_EDIT): { // edit item
			showDialog(DLG_ID_EDIT);
			return true;
		}
		case (MENU_ID_DELETE): { // delete item
			// ga.listItems.remove(posInTable);
			// long rowId = dbla.getRowId(new ListItem(current_str,""));
			ga.getDbla().removeList(posInTable);
			// ga.updateLists();
			updateAdapterData();
			// setTitle(index+" "+current_str+" "+listCursor.getCount()+" "+flag
			// +" "+rowId);

			return true;
		}
		}

		return false;
	}

	/*@Override
	public boolean onCreateOptionsMenu(Menu menu) {
		super.onCreateOptionsMenu(menu);

		MenuItem itemAdd = menu.add(0, C.MENU.COMPLETED, Menu.NONE, "已完成");
		MenuItem itemRem = menu.add(0, C.MENU.TRASH, Menu.NONE, "垃圾箱");

		// Assign icons
		// itemAdd.setIcon(R.drawable.add_new_item);
		// itemRem.setIcon(R.drawable.remove_item);
		// Allocate shortcuts to each of them.108
		// itemAdd.setShortcut(��0��, ��a��);
		// itemRem.setShortcut(��1��, ��r��);
		return true;
	}*/

	/*@Override
	public boolean onOptionsItemSelected(MenuItem item) {
		super.onOptionsItemSelected(item);

		Intent itt = null;
		// int index = myListView.getSelectedItemPosition();
		switch (item.getItemId()) {
		case C.MENU.COMPLETED: // completed task
			// setTitle("edit list");
			// Cursor csr =
			// ga.getDbta().fetchTasks(DBTaskAdapter.KEY_COMPLETED+"="+TaskItem.COMPLETED);
			itt = new Intent(ListAct.this, ViewTaskAct.class);

			itt.putExtra("list_index", -1);
			itt.putExtra("task_status", C.TASK.COMPLETED);

			startActivity(itt);

			return true;

		case C.MENU.TRASH: // deleted task
			// setTitle("remove list");
			itt = new Intent(ListAct.this, ViewTaskAct.class);

			itt.putExtra("list_index", -1);
			itt.putExtra("task_status", C.TASK.CANCELLED);

			startActivity(itt);

			return true;

		default:
			break;
		}

		return false;
	}*/

	@Override
	protected void onActivityResult(int requestCode, int resultCode, Intent data) {
		// TODO Auto-generated method stub
		switch (resultCode) {
		case RESULT_OK:
			break;
		default:
			break;
		}
		// super.onActivityResult(requestCode, resultCode, data);
	}

} // end class